package juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Guo
 * @Create 2020/8/5 13:20
 */
class Ticket  { //资源类

    private int number = 30;

    //可重入锁
    private Lock lock = new ReentrantLock();

    public void saleTicket() {

        lock.lock();
        try {
            if (number > 0 ) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第:" + (number--) +"\t还剩下" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

/**
 * 题目 三个售票员 卖出 30张票
 * 多线程编程企业级套路+模板
 */
public class SaleTicket {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();

        Thread t1 = new Thread();
        new Thread(() ->{for (int i = 1;i<=40; i++) { ticket.saleTicket(); }},"A").start();
        new Thread(() ->{for (int i = 1;i<=40; i++) { ticket.saleTicket(); }},"A").start();
        new Thread(() ->{for (int i = 1;i<=40; i++) { ticket.saleTicket(); }},"A").start();


      /*  new Thread(new Runnable()
        {
            @Override
            public void run() {
                for (int i = 1;i<=40; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start();

        new Thread(new Runnable()
        {
            @Override
            public void run() {
                for (int i = 1;i<=40; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();

        new Thread(new Runnable()
        {
            @Override
            public void run() {
                for (int i = 1;i<=40; i++) {
                    ticket.saleTicket();
                }
            }
        },"c").start();*/

    }
}